package com.wushi.lenovo.asia5b.app_ui.home.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.permissions.RxPermissions;
import com.mvp.base.BaseMvpFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.common.LocalManageUtil;
import com.mvp.refresh.AutoRefreshLayout;
import com.mvp.refresh.RefreshViewManager;
import com.mvp.utils.JsonUtil;
import com.mvp.utils.SharedPreferencesUtils;
import com.mvp.utils.ToastUtil;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.AppExtendsKt;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.ShopRepository;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.home.mvpview.HomeFragmentView;
import com.wushi.lenovo.asia5b.app_di.home.presenter.HomeFragmentPresenter;
import com.wushi.lenovo.asia5b.app_event.FacebookEvent;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_event.UpdateWisnStateEvent;
import com.wushi.lenovo.asia5b.app_model.h5.H5Bean;
import com.wushi.lenovo.asia5b.app_model.h5.H5FiexedAdBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5GoodsDetailBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5WishBean;
import com.wushi.lenovo.asia5b.app_model.h5.JsCall;
import com.wushi.lenovo.asia5b.app_model.other.H5VersionModel;
import com.wushi.lenovo.asia5b.app_ui.h5.H5Activity;
import com.wushi.lenovo.asia5b.app_ui.home.activity.SearchActivity;
import com.wushi.lenovo.asia5b.app_ui.home.activity.SnapActivity;
import com.wushi.lenovo.asia5b.app_ui.other.activity.MainActivity;
import com.wushi.lenovo.asia5b.app_ui.shopcar.activity.ShopCarActivity;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;
import com.wushi.lenovo.asia5b.app_utils.helper.H5Hepler;
import com.wushi.lenovo.asia5b.app_utils.webview_util.MyWebChromeClient;
import com.wushi.lenovo.asia5b.app_utils.webview_util.MyWebViewClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;

import static java.lang.String.format;
import static timber.log.Timber.d;

/**
 * ================================================
 * Created by ${chenyuexueer}
 * 时间： 2018/8/18.
 * 说明：HomeFragment界面
 * ================================================
 */
public class HomeFragment extends BaseMvpFragment<HomeFragmentView, HomeFragmentPresenter>
        implements HomeFragmentView {

    @BindView(R.id.webview_home)
    WebView mWebView;
    @BindView(R.id.auto_home)
    AutoRefreshLayout auto;
    @BindView(R.id.tv_home_shopcar_count)
    TextView tv_home_shopcar_count;
    @BindView(R.id.iv_nonet_bg)
    ImageView iv_nonet_bg;

    WebSettings webSettings;
    private H5GoodsDetailBean h5GoodsDetailBean;//商品列表跳转其他界面留一个该商品的标记
    private long nextJsTime = 0;//上一次点击的时间,禁止双击
    private static boolean isFirstAdv = true;//是否是第一次显示广告

    private boolean isPiFragment = false;
    private String genUrl = "index?";//根地址

    @Override
    protected int getLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            isPiFragment = getArguments().getBoolean("isPiFragment", false);
            if (isPiFragment) {
                isFirstAdv = false;
                genUrl = "mall_1688?";
            }
        }
        EventBus.getDefault().register(this);
        initView();
        initEvent();
    }

    @Override
    protected void lazyFetchData() {
        initData();
    }

    @Override
    protected void initView() {
        if (auto != null)
            ((RefreshViewManager) mActivity).addView(auto);
        //初始化actionbar
        initWebView();//初始化webview

        setShopNumber();

    }

    public void setShopNumber() {
        int number = ShopRepository.getShopCount();
        EyeUtils.setNums(tv_home_shopcar_count, UserRepository.isLogin() ? number : 0);
    }

    @Override
    protected void initData() {
        getPresenter().getH5Version();
    }

    @Override
    protected void initEvent() {
        if (auto != null)
            auto.setOnRefreshListener(refreshLayout -> {
                getPresenter().getH5Version();
                loadUrl();
            });
        //订阅购物车数量
        Disposable subscribe = ShopRepository.getShopCountOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    setShopNumber();
                });
        composite.add(subscribe);
    }

    private void loadUrl() {
        String url = H5Hepler.getH5_Url(genUrl);
        mWebView.loadUrl(url);
        if (auto != null)
            auto.finishRefresh();
    }


    @OnClick({
            R.id.ll_home_menu_vessel,
            R.id.ll_home_camera_vessel,
            R.id.cons_home_search_vessel,
            R.id.ll_home_shopcar_vessel
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            /**
             * 抽屉效果的打开
             */
            case R.id.ll_home_menu_vessel:
                ((MainActivity) getActivity()).openDrawerlayout();
                break;
            case R.id.ll_home_camera_vessel: {//拍照
                EyeUtils.tagPermission();
                new RxPermissions(getActivity())
                        .request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                startActivity(new Intent(getContext(), SnapActivity.class));
                            } else {
                                ToastUtil.showToast(getString(R.string.permission_error1));
                            }
                        });

            }
            break;
            case R.id.cons_home_search_vessel: {//搜索
                startActivity(new Intent(getContext(), SearchActivity.class));
            }
            break;
            case R.id.ll_home_shopcar_vessel: {//购物车
                if (UserRepository.isLogin(getContext())) {
                    startActivity(new Intent(getContext(), ShopCarActivity.class));
                }
            }
            break;
        }
    }

    private void showNetError(boolean loadSuccess) {
        if (!loadSuccess) {//加载webview失败
            iv_nonet_bg.setVisibility(View.VISIBLE);
            if (TextUtils.equals("en", LocalManageUtil.getAppLanguage())) {//如果是英文环境
                iv_nonet_bg.setImageResource(R.drawable.img_nonet_en);
            } else {
                iv_nonet_bg.setImageResource(R.drawable.img_nonet_cn);
            }
            iv_nonet_bg.setOnClickListener(v -> {
                auto.autoRefresh();
            });
        } else {
            iv_nonet_bg.setVisibility(View.GONE);
        }
        dismissLoadingBar("");
    }

    //初始化webview
    private void initWebView() {
        //初始化WebSettings
        initWebSettings();

        mWebView.setWebViewClient(new MyWebViewClient() {
//            @Override
//            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                H5Hepler.alterSSL(mActivity, view, handler, error);
//            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                d(format("--->>>>>>>>---onPageFinished:" + Thread.currentThread().getName()));
                if (activityWeakReference.get() != null) {
                    dismissLoadingBar("");
                }
                setCookie();
                mWebView.evaluateJavascript("javascript:window.Android.loadState('loadsuccess'+!!document.querySelector('#app'));", null);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                d(format("--->>>>>>>>---onReceivedError"));
                if (activityWeakReference.get() != null) {
                    dismissLoadingBar("");
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Timber.d("--->>>>>>>>---onPageStarted");
                if (activityWeakReference.get() != null) {
                    showLoadingBar(null);
                }
            }
        });
        mWebView.setWebChromeClient(new MyWebChromeClient());
        String url = "";
        if (isFirstAdv) {
            url = H5Hepler.getH5_Url("index?advert=1");
        } else {
            url = H5Hepler.getH5_Url(genUrl);
        }
        isFirstAdv = false;
        mWebView.loadUrl(url);

        //与JS的交互
        doJavaScript();

    }

    private void setCookie() {
        if (mWebView == null) {
            return;
        }
        String cookie = (String) SharedPreferencesUtils.getData("cookie", "");
        if (!TextUtils.isEmpty(cookie)) {
            Type type = new TypeToken<List<H5FiexedAdBean.FiexedAdItem>>() {
            }.getType();
            List<H5FiexedAdBean.FiexedAdItem> list = JsonUtil.INSTANCE.jsonToAny(cookie, type);
            if (list != null && list.size() > 0) {
                String s = JsonUtil.INSTANCE.anyToJson(list);
                String js = String.format(CommonConstant.fiexedAd, s);
                mWebView.evaluateJavascript(js, null);
            }
        }
    }


    //初始化WebSettings
    private void initWebSettings() {
        //声明WebSettings子类
        webSettings = mWebView.getSettings();

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口, 设置允许JS弹窗
        webSettings.setDomStorageEnabled(true);//DOM Storage缓存

        //支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);

        //设置自适应屏幕，两者合用（下面这两个方法合用）
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setTextZoom(100); // 就可以禁止缩放，按照百分百显示。

        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); //打开webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件

        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        webSettings.setAppCacheEnabled(false);//是否使用缓存
        webSettings.setBlockNetworkImage(false);
        //为什么要加这句，http://blog.csdn.net/u013320868/article/details/52837671 访问这个就可以了
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //设置允许加载混合内容
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }


    //与JS的交互
    @SuppressLint("JavascriptInterface")
    public void doJavaScript() {

        JsCall jsCall1 = new JsCall() {
            @Override
            public void loadStateByMain(String param) {
                super.loadStateByMain(param);
                showNetError(!TextUtils.equals("loadsuccessfalse", param));
            }

            @Override
            public void callbackParam(String param) {
                if (auto != null && auto.getState() != RefreshState.None) {
                    return;
                }
                if ((System.currentTimeMillis() - nextJsTime) < 1000) {//如果两次点击时间间隔1S,仅算第一次
                    return;
                }
                nextJsTime = System.currentTimeMillis();
                //判断商品详情,判断第三方商城,判断轮播图
                H5Bean h5Bean = H5Hepler.parseUrl(getActivity(), param);
                if (h5Bean != null) {
                    if (h5Bean instanceof H5WishBean) {
                        H5WishBean h5WishBean = (H5WishBean) h5Bean;
                        d("--->>>>>>>>---开始添加收藏:" + h5WishBean.getGoods_id());
                        if (UserRepository.isLogin(getContext())) {
                            getPresenter().changeWishType(h5WishBean);
                        }
                    } else if (h5Bean instanceof H5GoodsDetailBean) {
                        h5GoodsDetailBean = (H5GoodsDetailBean) h5Bean;
                    }
                }
            }
        };
        mWebView.addJavascriptInterface(jsCall1, H5Activity.H5_JSCALL_NAME);
    }


    protected void changeWishType(WebView webView, H5WishBean h5WishBean) {
        String js = "";
        if (TextUtils.equals(h5WishBean.getProduct_wishlist(), "1")) {//当前状态已收藏,那么就删除收藏
            js = format(CommonConstant.WISHNORMAL2, h5WishBean.get_index(), h5WishBean.getGoods_id());
        } else {//当前状态未收藏,那么就添加收藏
            js = format(CommonConstant.WISHPRESS2, h5WishBean.get_index(), h5WishBean.getGoods_id());
        }
        d("--->>>>>>>>---执行js代码:" + js);
        webView.evaluateJavascript(js, null);
    }

    @Override
    public void changeWishTypeResult(ResultModel resultModel, H5WishBean h5WishBean, boolean finalIsWish) {
        if (resultModel.isSuccess()) {
            ToastUtil.showToast(resultModel.getMsg());
            EventBus.getDefault().post(new UpdateWisnStateEvent(h5WishBean.getGoods_id(), finalIsWish));
            changeWishType(mWebView, h5WishBean);
        }
    }

    @Override
    public void getH5VersionResult(ResultModel<H5VersionModel> resultModel) {
        if (resultModel.isSuccess()) {
            H5VersionModel h5VersionModel = resultModel.getData();
            if (h5VersionModel != null) {
                int oldH5Version = AppExtendsKt.getH5Version();
                d("--->>>>>>>>---H5版本更新" + String.format("oldVersion:%d,newVersion:%d", oldH5Version, h5VersionModel.h5_web_version));
                if (h5VersionModel.h5_web_version > oldH5Version) {
                    AppExtendsKt.setH5Version(h5VersionModel.h5_web_version);
                    mWebView.clearCache(true);
                    mWebView.clearFormData();
                    loadUrl();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onUpdateWishEvent(UpdateWisnStateEvent event) {
        if (event != null) {
            changeWishType(mWebView, "0", event.product_id, event.isWish);
//            if (h5GoodsDetailBean != null) {
//                String goods_url = h5GoodsDetailBean.getGoods_url();
//                if (!TextUtils.isEmpty(goods_url) && goods_url.contains(event.product_id)) {
//                }
//            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        //登录状态有改变
        if (event != null) {
            loadUrl();
            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                d("--->>>>>>>>---登录成功");
                FacebookEvent.Companion.login();
            } else if (TextUtils.equals(event.loginState, CommonConstant.LOGOUT_SUCCESS)) {
                d("--->>>>>>>>---退出登录");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onFacebookEvent(FacebookEvent event) {
        //登录状态有改变
        if (event != null) {
            if (!isPiFragment) {
                mWebView.evaluateJavascript(event.getJavascript(), null);
                d("--->>>>>>>>---执行facebook脚本日志:" + event.getJavascript());
            }
        }
    }

    /**
     * @param webView
     * @param index   商品列表的角标值
     * @param isWish  设置收藏后的状态
     */
    protected void changeWishType(WebView webView, String index, String goods_id, boolean isWish) {
        String js = "";
        if (!isWish) {//设置状态未非收藏
            js = format(CommonConstant.WISHNORMAL2, index, goods_id);
        } else {//当前状态未收藏,那么就添加收藏
            js = format(CommonConstant.WISHPRESS2, index, goods_id);
        }
        d("--->>>>>>>>---执行js代码:" + js);
        webView.evaluateJavascript(js, null);
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

}
